package com.supplychain.financial.parent.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.*;

public class WebUtils {
   
	
	private static Map<String,String> mineTypeDef = new HashMap<String,String>(){
		{
			put(".xls","application/vnd.ms-excel");
			put(".pdf","application/pdf");
			put(".zip","application/pdf");
			put(".doc","application/msword");
			put(".docx","application/msword");
			put(".dot","application/msword");
		};
	};
	
	//根据文件类型获取Context-Type
	public static String getContextType(String fileExt){
		if(mineTypeDef.containsKey(fileExt))
			return mineTypeDef.get(fileExt).toString();
		return "application/octet-stream";
	}
	
	public static String post(HttpClient httpClient, String url,Map params) throws ConnectException, UnknownHostException, Exception{
		HttpPost httpost = postForm(url,params);
		return invoke(httpClient, httpost);
	}
	
	public static String get(HttpClient httpClient, String url) throws ConnectException, UnknownHostException, Exception{
		HttpGet get = new HttpGet(url);  
		return invoke(httpClient, get);
	}
	
    private static String invoke(HttpClient httpclient,  HttpUriRequest httpost) throws Exception {  
    	HttpResponse response = sendRequest(httpclient, httpost);  
    	if(isRedirect(response.getStatusLine().getStatusCode())){
    		Header header=response.getFirstHeader("Location");
            //重定向地址
            String location =  header.getValue();
            //然后再对新的location发起请求即可
            httpost = new HttpPost(location);  
            invoke(httpclient,httpost);
    	}
        String body = parseResponse(response);  
        return body;  
    }  
    
    private static HttpPost postForm(String url, Map<String, String> params){  
        HttpPost httpost = new HttpPost(url);  
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();  
          if(params != null && params.size()>0){
        	  Set<String> keySet = params.keySet();  
  	        	for(String key : keySet) {  
  	        		nvps.add(new BasicNameValuePair(key, params.get(key)));  
  	        }  
          }
        try {  
            httpost.setEntity(new UrlEncodedFormEntity(nvps,Charset.forName("UTF-8")));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
          
        return httpost;  
    }  
    
    private static String parseResponse(HttpResponse response) throws IOException {  
        HttpEntity entity = response.getEntity();  
        String body = null;  
        try {  
        	InputStream in=response.getEntity().getContent();
            body =IOUtils.toString(in);
            in.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        return body;  
    }  
  
    private static HttpResponse sendRequest(HttpClient httpclient,HttpUriRequest httpost) {  
        HttpResponse response = null;  
        try {  
            response = httpclient.execute(httpost);  
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        return response;  
    }  
	 
    private static boolean isRedirect(int statusCode) {
		if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)
			return true;
		return false;
	}
	 
	
	/**
	 * 从URL获取所有参数列表
	 * @param request
	 * @return
	 */
	public static HashMap getAllParamMap(HttpServletRequest request){
		HashMap hashMap = new HashMap();
		Enumeration enums = request.getParameterNames();
		String paramName = null;
		String paramValue = null;

		while (enums.hasMoreElements()) {
			paramName = (String) enums.nextElement();
			paramValue = (String) request.getParameter(paramName);
			hashMap.put(paramName, paramValue);
		} 
		return hashMap;
	}
	
	/**
	 * 从消息流获取所有参数列表
	 * @param request
	 * @return
	 */
	public static Map getAllParamFromStream(HttpServletRequest request) {
		Map result = new HashMap();
		InputStream is = null;
		try {
			is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			// 读取HTTP请求内容
			String buffer = null;
			StringBuffer sb = new StringBuffer();
			while ((buffer = br.readLine()) != null) {
				sb.append(buffer);
			}
			result = new ObjectMapper().readValue(sb.toString(), Map.class);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getEasyUiJsonData(List values){ 
		return getEasyUiJsonData(values,values.size());
	}
	
	public static String getEasyUiJsonData(List values,int total){
		Map map = new HashMap();
		map.put("total", total);
		map.put("rows", values);  
		try {
			return new ObjectMapper().writeValueAsString(map);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
     * 将数据转换成请求格式
     * @param data
     * map 数据
     * @return
     * 返回结果name1=value1&name2=value2 的形式
     */
	public static String convertMap2String(Map<String, String> data) {
		Map tree = new HashMap();
		Iterator it = data.entrySet().iterator(); 
		StringBuffer sb = new StringBuffer();
		while (it.hasNext()) {
			Map.Entry en = (Map.Entry) it.next();
			sb.append(new StringBuilder().append((String) en.getKey()).append("=").append((String) en.getValue()).append("&").toString());
		}
		return sb.substring(0, sb.length() - 1);
	}
	
	 /**
     * 将数据转换成请求格式
     * @param res
     *   请求数据name1=value1&name2=value2
     * @return
     *    返回结果map
     */
	public static Map<String, String> convertResultString2Map(String res) {
		Map map = null;
		if ((null != res) && (!("".equals(res.trim())))) {
			String[] resArray = res.split("&");
			if (resArray.length > 0) {
				map = new HashMap(resArray.length);
				String[] arry = resArray;
				int len = arry.length;
				for (int i = 0; i < len; ++i) {
					String arrayStr = arry[i];
					if (null != arrayStr || !"".equals(arrayStr.trim())) {
						int index = arrayStr.indexOf("=");
						if (index > -1)
							map.put(arrayStr.substring(0, index), arrayStr.substring(index + 1));
					}
				}
			}
		}
		return map;
	}
	
}
